﻿using System;

namespace Sencha.Serialization.Bson
{

	/// <summary>
	/// Representation of JS Code in BSON. This type is immutable by design
	/// </summary>
	[TypeSerializer(typeof(Serializers.BsonJavaScriptSerializer))]
	public class BsonJavaScript : IEquatable<BsonJavaScript>
	{
		public string Code { get; private set; }

		public BsonJavaScript()
			: this(string.Empty)
		{

		}
		public BsonJavaScript(string code)
		{
			if (code == null)
				throw new ArgumentNullException("code");

			this.Code = code;
		}

		#region IEquatable<BsonJavaScript> Members

		public override bool Equals(object obj)
		{
			return this.Equals(obj as BsonJavaScript);
		}

		public override int GetHashCode()
		{
			return this.Code.GetHashCode();
		}

		public bool Equals(BsonJavaScript other)
		{
			if (other == null)
				return false;

			return this.Code.Equals(other.Code);
		}

		#endregion

		public static bool operator ==(BsonJavaScript a, BsonJavaScript b)
		{
			if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
				return false;
			else if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
				return false;
			else
				return a.Equals(b);

		}
		public static bool operator !=(BsonJavaScript a, BsonJavaScript b)
		{
			return !(a == b);
		}

		public override string ToString()
		{
			return string.Format("javascript: {0}", this.Code != null && this.Code.Length > 20 ? this.Code.Substring(0, 20) + "..." : this.Code);
		}
	}
}
